package com.kplan.join.model.dao;

import com.kplan.join.model.MemberDto;
import com.kplan.util.db.DBClose;
import com.kplan.util.db.DBConnection;

import java.sql.*;

public class JoinDao {

	private static JoinDao dao;
	
	static {
		dao = new JoinDao();
	}
	
	private JoinDao(){}
	
	public static JoinDao getInstance() {
		return dao;
	}
	
	public int register(MemberDto memberDto) {
		int cnt = 0;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			conn = DBConnection.makeConnection();
			String sql = "insert into member (email, nick, name, pass, age, gender, tel1, tel2, tel3, visited, togo, point, psum, status, bcode, max_planner) \n";
			sql += "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, 1, 0, 1)";
			pstmt = conn.prepareStatement(sql);
			int idx = 0;
			pstmt.setString(++idx, memberDto.getEmail());
			pstmt.setString(++idx, memberDto.getNick());
			pstmt.setString(++idx, memberDto.getName());
			pstmt.setString(++idx, memberDto.getPass());
			pstmt.setInt(++idx, memberDto.getAge());
			pstmt.setInt(++idx, memberDto.getGender());
			pstmt.setString(++idx, memberDto.getTel1());
			pstmt.setString(++idx, memberDto.getTel2());
			pstmt.setString(++idx, memberDto.getTel3());
			pstmt.setString(++idx, memberDto.getVisited());
			pstmt.setString(++idx, memberDto.getTogo());
			
			cnt = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBClose.close(conn, pstmt);
		}
		return cnt;
	}
	
	public int emailCheck(String email) {
		int cnt = 0;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = DBConnection.makeConnection();
			String sql = "select count(email) \n";
			sql += "from member \n";
			sql += "where email = '" + email + "'";
			pstmt = conn.prepareStatement(sql);
			
			rs = pstmt.executeQuery();
			rs.next();
			cnt = rs.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBClose.close(conn, pstmt, rs);
		}
		return cnt;
	}

	public int nickCheck(String nick) {
		int cnt = 0;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = DBConnection.makeConnection();
			String sql = "select count(nick) \n";
			sql += "from member \n";
			sql += "where nick = '" + nick + "'";
			pstmt = conn.prepareStatement(sql);
			
			rs = pstmt.executeQuery();
			rs.next();
			cnt = rs.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBClose.close(conn, pstmt, rs);
		}
		return cnt;
	}
	
}
